<?php

namespace app\common\model\course;

use app\common\model\question\Option;
use think\Model;


class Qusetion extends Model
{





    // 表名
    protected $name = 'question';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = false;

    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'type_text',
        'image_str',
    ];
    public function getImageStrAttr($value, $data)
    {
        return isset($data['image']) && $data['image'] ? cdnurl($data['image'], true) : '';
    }

    protected static function init()
    {
        self::beforeUpdate(function ($row) {
            $changed = $row->getChangedData();
            if (isset($changed['category_id']) && $changed['category_id']) {
                $row->__set('type', Category::where('id', $changed['category_id'])->value('type'));
            }
        });
        self::beforeInsert(function ($row) {
            $changed = $row->getChangedData();
            if (isset($changed['category_id']) && $changed['category_id']) {
                $row->__set('type', Category::where('id', $changed['category_id'])->value('type'));
            }
        });
    }
    public function getSubjectList()
    {
        return ['1' => __('Subject 1'), '2' => __('Subject 2'), '3' => __('Subject 3')];
    }


    public function getTypeList()
    {
        return ['1' => __('Type 1'), '2' => __('Type 2')];
    }

    public function getOptionsAttr($v, $d)
    {
        return json_encode(Option::where('q_id', $d['id'])->select());
    }

    public function getTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['type']) ? $data['type'] : '');
        $list = $this->getTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function option()
    {
        return $this->hasMany(Option::class, 'q_id', 'id');
    }


    public function category()
    {
        return $this->belongsTo('Category', 'category_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
}
